<template>
	<view class="service_list">
		<view class="order-card" v-if="orderId">
			<view class="card_status_icon">关联订单</view>
			<view class="order-header">
				<view class="shop-info">
					<view class="shop-name">{{ orderInfo.studioName }}</view>
					<view class="order-time">{{ orderInfo.orderId }}</view>
				</view>
				<text class="order-status">{{ getStatusText(orderInfo.status) }}</text>
			</view>
			<view class="order_server_info">
				<scroll-view class="multiple_specs_scroll" scroll-x="true" v-if="orderInfo?.orderGoodsSkuVOSAll?.length > 1">
					<view class="server_info_box" v-for="val in orderInfo.orderGoodsSkuVOSAll" :key="val.skuId">
						<image class="server_img" :src="val.goodsAvatar"></image>
						<view class="specs_box">{{ val.goodsName }}</view>
						<view class="server_price">×{{ val.serviceDays || 1 }}</view>
					</view>
				</scroll-view>
				<view class="server_info_box" v-else>
					<image class="server_img" :src="orderInfo?.orderGoodsSkuVOSAll?.[0]?.goodsAvatar"></image>
					<view class="name_price">
						<view class="server_name">{{ orderInfo?.orderGoodsSkuVOSAll?.[0]?.goodsName }}</view>
						<view class="specs_price">
							<text class="server_specs">{{ orderInfo?.orderGoodsSkuVOSAll?.[0]?.serviceTime }} | ¥{{ orderInfo?.orderGoodsSkuVOSAll?.[0]?.price }}</text>
							<!--<text class="server_price"></text>-->
						</view>
					</view>
				</view>
				<view class="order_price_box">
					<view class="order_price">¥{{ orderInfo.payAmount }}</view>
					<view class="pay_text">{{ getPayText(orderInfo.status) }}</view>
				</view>
			</view>
			<view class="order-details">
				<view class="detail-item">
					<view class="label">宠物{{ orderInfo.petNum }}只</view>
					<view class="value">
						<text v-for="(val, valIndex) in orderInfo.petList" :key="valIndex">
							{{ val.petNickName }}({{ getPetTypeText(val.type) }})
							<text style="margin: 0 8rpx" v-if="valIndex < orderInfo.petList.length - 1">|</text>
						</text>
					</view>
				</view>
				<view class="detail-item">
					<view class="label">服务时间</view>
					<view class="value">{{ orderInfo.serviceStartTime }}</view>
				</view>
				<view class="detail-item">
					<view class="label">服务地址</view>
					<view class="value">{{ orderInfo.address }}</view>
				</view>
			</view>
			<view class="pet_companion_teacher_box" v-if="orderInfo.petsitterUserId">
				<view class="pet_teacher_title">陪宠师</view>
				<view class="pet_teacher_info_box">
					<image class="pet_teacher_img" :src="orderInfo.petsitterAvatar"></image>
					<view class="pet_teacher_name">{{ orderInfo.petsitterNickName }}</view>
				</view>
			</view>
		</view>
		<view class="value-service">
			<view class="value-service__header">订购增值服务</view>

			<view class="value-service__list">
				<view class="value-service__card" v-for="(item, index) in selectedExtraServiceListByStore" :key="index">
					<view class="value-service__main">
						<image class="value-service__image" :src="item.goods.thumPic" mode="aspectFill" />
						<view class="value-service__content">
							<view class="value-service__title">{{ item.goods.name }}</view>
							<view class="value-service__info">
								<view class="value-service__price">¥{{ item.goodsSkuList?.[0]?.price }}/次</view>
								<view class="value-service__quantity">× {{ computedServiceCount(item.config)}}</view>
							</view>
						</view>
					</view>
					<view class="value-service__schedule" v-if="item.config?.length > 0">
						<view class="value-service__schedule-item" v-for="(config, configIndex) in item.config" :key="configIndex">
							<text v-if="item.goods.pickServicePet == 1">{{ config.petNickName }}</text>
							<text v-if="item.goods.pickServicePet == 1 && item.goods.pickServiceDate == 1">-</text>
							<text v-if="item.goods.pickServiceDate == 1">{{ formatDate(config.date) }}</text>
						</view>
					</view>
					<view class="value-service__divider"></view>
				</view>
			</view>
		</view>
		<view class="price-summary">
			<view class="price-item">
				<view class="item-label">增值服务</view>
				<view class="item-price">¥{{ extraServiceFee }}</view>
			</view>
			<view class="price-total">
				<view class="total-label">总计:</view>
				<view class="total-price">¥{{ extraServiceFee }}</view>
			</view>
		</view>
		<view class="footer-bar">
			<view class="total-price">
				<text class="label">合计:</text>
				<text class="price">¥{{ extraServiceFee }}</text>
			</view>
			<view class="submit-btn" @tap="handleSubmit">确认下单</view>
		</view>
		<paymentPopup ref="paymentPopupRef" @confirm="paymentCompleted" @cancel="failToPay" @fail="failToPay"></paymentPopup>
	</view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { payment } from '@/hooks/usePay/index.ts';
import api from '@/api';
import BigNumber from 'bignumber.js';
import dayjs from 'dayjs';
import { useOrderStoreToRefs, resetUseOrderStore } from '@/store/useOrderStore';
const { selectedExtraServiceListByStore } = useOrderStoreToRefs();

const orderId = ref('');
const orderInfo = ref({});
const petsList = ref([]);
const paymentPopupRef = ref();

const extraServiceFee = computed(() => {
	const result = selectedExtraServiceListByStore.value.reduce((acc, item) => {
		const count = computedServiceCount(item.config)
		return new BigNumber(item.goodsSkuList?.[0]?.price)
			.times(count)
			.plus(acc)
			.toFixed(2);
	}, 0);
	return Number(result) || 0;
});

onLoad(async (options) => {
	handleSubmit = preventRepeat(handleSubmit);

	orderId.value = options.orderId;
	await getOrderInfo();
	petsList.value = orderInfo.value.petList;
});

const getOrderInfo = async () => {
	const { data } = await api({
		method: 'get',
		url: `/mall/order/order-detail/dayOrderDetail`,
		data: {
			id: orderId.value
		}
	});
	orderInfo.value = data;
};

let handleSubmit = async () => {
	const res = await api({
		method: 'post',
		url: `/mall/order/creat/ext`,
		data: {
			orderDetailId: orderId.value,
			extSkuList: formatExtraServiceList()
		}
	});
	console.log(res);
	if (res.code == 0) {
		orderId.value = res.data;
		uni.showModal({
			title: `提示`,
			content: `已下单成功，是否确认付款？`,
			cancelText: '暂不付款',
			confirmText: '确认付款',
			success: async (status) => {
				if (status.cancel) {
					uni.redirectTo({
						url: `/pages/petsOrder/petsList/index?orderStatus=0`
					});
					return;
				}
				toPay();
			}
		});
		return;
	} else {
		uni.showToast({
			icon: 'none',
			title: res.msg || ''
		});
	}
};

const toPay = async () => {
	// #ifndef MP-TOUTIAO
	paymentPopupRef.value.open({
		orderId: orderId.value,
		payAmount: extraServiceFee,
		payBusinessType: 1,
		checkOrderType: 'petsService'
	});
	// #endif

	// #ifdef MP-TOUTIAO
	const isSuccessed = await payment({
		orderId: orderId.value,
		payBusinessType: 1,
		payType: 1,
		amount: extraServiceFee
	});
	if (isSuccessed) {
		uni.showToast({
			title: '支付成功'
		});
		uni.redirectTo({
			url: `/pages/payment/successfulPayment/index?orderId=${orderId.value}`
		});
	} else {
		uni.showToast({
			title: '支付失败'
		});
		uni.redirectTo({
			url: `/pages/petsOrder/petsList/index?orderStatus=0`
		});
	}

	// 清除缓存
	// addressInfo.value = {};
	// petsInfo.value = [];
	resetUseOrderStore();
	// #endif
};

const paymentCompleted = async (data) => {
	// 清除缓存
	// addressInfo.value = {};
	// petsInfo.value = [];
	resetUseOrderStore();
	uni.redirectTo({
		url: `/pages/payment/successfulPayment/index?orderId=${data.orderId}`
	});
	
};
const failToPay = () => {
	uni.showToast({
		title: '支付失败'
	});
	uni.redirectTo({
		url: `/pages/petsOrder/petsList/index?orderStatus=0`
	});
};

const formatExtraServiceList = () => {
	if (selectedExtraServiceListByStore.value.length == 0) return [];
	const formatList = selectedExtraServiceListByStore.value.map((item) => {
		const { skuId, config } = item;
		if (config.length > 0) {
			// 将config中同一天的配置合并
			const dateList = [];
			config.forEach((configItem) => {
				const { date, petId } = configItem;
				const findItem = dateList.find((dateItem) => dateItem.date == date);
				if (!findItem) {
					dateList.push({
						date: date,
						petId: petId
					});
				} else {
					findItem.petId += `,${petId}`;
				}
			});
			item.dateList = dateList;
		}
		return item;
	});
	// 每个日期生成一个增值服务配置
	const resultList = [];
	formatList.forEach((item) => {
		if (item && item.dateList && item.dateList.length > 0) {
			item.dateList.forEach((dateItem) => {
				resultList.push({
					skuId: item.goodsSkuList[0].id,
					petIds: dateItem.petId,
					date: dateItem.date
				});
			});
		} else {
			resultList.push({
				skuId: item.goodsSkuList[0].id,
				petIds: '',
				date: ''
			});
		}
	});
	return resultList;
};

// 计算服务次数，按天算，不按宠物算
const computedServiceCount = (data) => {
	const list = data.filter(item => item.date)
	return list.length || 1
}

const getPayText = (type) => {
	switch (type) {
		case 4:
		case 5:
			return '合计';
		default:
			return '实付';
	}
};

const getStatusText = (status) => {
	switch (status) {
		case 1:
			return '待服务';
		case 2:
			return '服务中';
		case 3:
			return '已完成';
		case 4:
			return '已取消';
		case 5:
			return '已取消';
		default:
			return '';
	}
};

const getPetTypeText = (type) => {
	switch (type) {
		case 0:
			return '猫';
		case 1:
			return '狗';
		default:
			return '其他';
	}
};

const getPetName = (petId) => {
	return petsList.value.find((pet) => pet.id === petId)?.petNickName;
};

const formatDate = (date) => {
	return dayjs(date).format('MM/DD');
};

// 防止异步函数执行过程中，重复执行
// 传入的函数必须是promise或者是async函数并决策，
const preventRepeat = (fn) => {
	let isDoing = false;
	return async function () {
		if (isDoing) return;
		isDoing = true;
		// try catch 防止promise抛出错误
		try {
			// 防止this劫持
			await fn.apply(this, arguments);
		} catch (e) {
		} finally {
			// 加定时器是因为接口请求完后到弹窗遮罩出来之前，有一瞬间可以触发点击事件
			setTimeout(() => {
				isDoing = false;
			}, 1000);
		}
	};
};
</script>

<style lang="scss" scoped>
.service_list {
	padding: 32rpx;
	background: #f9f6f6;
	min-height: 100vh;
	box-sizing: border-box;
	padding-bottom: calc(134rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(134rpx + env(safe-area-inset-bottom));
}

.order-card {
	background: #ffffff;
	border-radius: 24rpx;
	padding: 80rpx 32rpx 40rpx;
	margin-bottom: 24rpx;
	position: relative;

	.card_status_icon {
		position: absolute;
		top: 0;
		left: 0;
		background: #6363ff;
		color: #ffffff;
		font-size: 26rpx;
		padding: 12rpx 36rpx;
		border-radius: 24rpx 0 24rpx 0;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 48rpx;

		.shop-info {
			line-height: 1;
			.shop-name {
				font-weight: bold;
				font-size: 32rpx;
				color: #1b2120;
				margin-bottom: 16rpx;
			}

			.order-time {
				font-size: 24rpx;
				color: #808080;
			}
		}

		.order-status {
			font-size: 26rpx;
			color: #6363ff;
		}
	}

	.order-content {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;

		.service-image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 16rpx;
			margin-right: 16rpx;
		}

		.service-info {
			flex: 1;

			.service-name {
				font-weight: 500;
				font-size: 32rpx;
				color: #1b2120;
				margin-bottom: 24rpx;
			}

			.service-price {
				font-size: 26rpx;
				color: #7c807f;
			}
		}

		.total-price {
			padding: 26rpx 16rpx;
			text-align: center;
			box-shadow: -8rpx 0 16rpx -8rpx rgba(0, 0, 0, 0.15);

			.price {
				font-weight: bold;
				font-size: 28rpx;
				color: #1b2120;
			}

			.price-label {
				font-size: 24rpx;
				color: #7c807f;
				margin-top: 16rpx;
			}
		}
	}

	.order_server_info {
		display: flex;
		justify-content: space-between;
		margin-top: 48rpx;

		.server_info_box {
			display: flex;
			align-items: center;
			flex-direction: row;
			width: calc(100% - 120rpx - 16rpx);

			.server_img {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
			}

			.name_price {
				margin-left: 16rpx;
				max-width: calc(100% - 120rpx - 16rpx);

				.server_name {
					font-weight: bold;
					font-size: 32rpx;
					color: #1b2120;
				}

				.specs_price {
					font-weight: 400;
					font-size: 26rpx;
					color: #7c807f;
					margin-top: 24rpx;
					text-overflow: ellipsis;
					white-space: nowrap;
					overflow: hidden;

					.server_specs {
					}

					.server_price {
					}
				}
			}
		}

		.multiple_specs_scroll {
			white-space: nowrap;
			width: calc(100% - 128rpx);

			.server_info_box {
				display: inline-block;
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				position: relative;
				margin-right: 16rpx;

				.server_img {
					width: 120rpx;
					height: 120rpx;
					border-radius: 12rpx;
				}

				.specs_box {
					position: absolute;
					top: 8rpx;
					left: 8rpx;
					max-width: 98rpx;
					background: #f9f6f6;
					border-radius: 4rpx;
					font-weight: 400;
					font-size: 18rpx;
					color: #1b2120;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.server_price {
					position: absolute;
					bottom: 0;
					right: 0;
					padding: 8rpx 10rpx;
					box-sizing: border-box;
					background: rgba(0, 0, 0, 0.35);
					border-radius: 24rpx 0rpx 24rpx 0rpx;
					font-weight: bold;
					font-size: 18rpx;
					color: #ffffff;
				}
			}
		}

		.order_price_box {
			width: 128rpx;
			padding: 0 16rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			box-shadow: -12rpx 0 20rpx -18rpx rgba(0, 0, 0, 0.2);

			.order_price {
				font-weight: bold;
				font-size: 28rpx;
				color: #1b2120;
			}

			.pay_text {
				font-weight: 400;
				font-size: 24rpx;
				color: #7c807f;
				margin-top: 16rpx;
			}
		}
	}

	.order-details {
		padding: 32rpx 24rpx;
		border: 2rpx solid #f9f6f6;
		border-radius: 16rpx 16rpx 16rpx 16rpx;

		.detail-item {
			display: flex;
			margin-bottom: 40rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.label {
				font-weight: bold;
				font-size: 24rpx;
				color: #5c5e5e;
				width: 120rpx;
				flex-shrink: 0;
			}

			.value {
				font-size: 24rpx;
				color: #7c807f;
				flex: 1;
			}
		}
	}
}

.value-service {
	background: #ffffff;
	padding: 40rpx 32rpx;
	border-radius: 24rpx;

	.value-service__header {
		font-weight: bold;
		font-size: 32rpx;
		color: #1b2120;
		padding-bottom: 48rpx;
		border-bottom: 1rpx solid #e4e6e6;
		margin-bottom: 48rpx;
	}

	.value-service__list {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}

	.value-service__card {
		margin-bottom: 16rpx;

		&:last-child {
			margin-bottom: 0;

			.value-service__divider {
				display: none;
			}
		}
	}

	.value-service__main {
		display: flex;
		align-items: flex-start;
		margin-bottom: 16rpx;
	}

	.value-service__image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 24rpx;
		margin-right: 32rpx;
	}

	.value-service__content {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.value-service__title {
		font-weight: bold;
		font-size: 30rpx;
		color: #1b2120;
		margin-bottom: 38rpx; // 调整标题下方间距
	}

	.value-service__info {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.value-service__price {
		font-size: 26rpx;
		color: #666;
	}

	.value-service__quantity {
		font-weight: bold;
		font-size: 26rpx;
		color: #1b2120;
	}

	.value-service__schedule {
		margin-left: 154rpx;
		background-color: #f5f6f7;
		border-radius: 12rpx;
		padding: 24rpx;
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 24rpx;

		.value-service__schedule-item {
			font-size: 24rpx;
			color: #7c807f;
			margin-bottom: 8rpx;

			&:last-child {
				margin-bottom: 0;
			}
		}
	}

	.value-service__divider {
		margin-left: 154rpx;
		height: 1rpx;
		background: #e4e6e6;
		margin-top: 48rpx;
	}
}

.price-summary {
	margin-top: 24rpx;
	background: #ffffff;
	padding: 32rpx 24rpx;
	border-radius: 24rpx;

	.price-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 32rpx;
		border-bottom: 1rpx solid #e4e6e6;
		margin-bottom: 32rpx;

		.item-label {
			font-size: 28rpx;
			color: #5c5e5e;
		}

		.item-price {
			font-size: 28rpx;
			color: #5c5e5e;
		}
	}

	.price-total {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-weight: bold;
		font-size: 28rpx;
		color: #1b2120;
	}
}

.footer-bar {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100%;
	background: #ffffff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 6rpx 32rpx 0;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
	box-sizing: border-box;

	.total-price {
		display: flex;
		align-items: center;
		margin-right: 76rpx;

		.label {
			font-size: 24rpx;
			color: #1b2120;
			font-weight: 500;
		}

		.price {
			font-weight: bold;
			font-size: 32rpx;
			color: #1b2120;
			margin-left: 8rpx;
		}
	}

	.submit-btn {
		flex: 1;
		height: 88rpx;
		background: linear-gradient(90deg, #ff6188 0%, #ff5252 100%);
		border-radius: 44rpx;
		color: #ffffff;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
	}
}

.pet_companion_teacher_box {
	width: 100%;
	background: #ffffff;
	display: flex;
	align-items: center;
	border-radius: 24rpx;
	padding: 28rpx 24rpx;
	box-sizing: border-box;
	margin-bottom: 24rpx;
	margin-top: 24rpx;
	border: 2rpx solid #f9f6f6;

	.pet_teacher_title {
		font-weight: bold;
		font-size: 24rpx;
		color: #5C5E5E;
		margin-right: 32rpx;
	}

	.pet_teacher_info_box {
		display: flex;
		align-items: center;

		.pet_teacher_img {
			width: 32rpx;
			height: 32rpx;
			border-radius: 50%;
			margin-right: 8rpx;
		}
		
		.pet_teacher_name {
			font-size: 24rpx;
			color: #7C807F;
		}

	}
}
</style>
